<template>
  <div class="app-container">
    <el-form
      :inline="true"
    >
      <el-form-item
        :label="$t('area.Layer')"
        prop="postName"
      >
        <treeselect
          v-model="mapId"
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :max-height="600"
          :options="mapTreeData"
          :default-expand-level="1"
          @input="nodeClick"
        />
      </el-form-item>
      <el-form-item
        :label="$t('history.date')"
        prop="postName"
      >
        <el-date-picker
          v-model="timeValue1"
          size="small"
          type="datetime"
          :placeholder="$t('operating.StartTime')"
          style="width:200px;"
          @change="change1"
        />
        -
        <el-date-picker
          v-model="timeValue2"
          type="datetime"
          size="small"
          :placeholder="$t('operating.EndTime')"
          style="width:200px;"
          @change="change2"
        />

      </el-form-item>
      <el-form-item
        :label="$t('history.objValue')"
        prop="postName"
      >
        <el-select
          v-model="value1"
          multiple
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

      </el-form-item>

      <el-form-item>
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="query"
        >{{ $t("operating.search") }}</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-header>

        <div class="handle-box">
          <span>{{$t('area.Layer')}}:</span>
          <treeselect v-model="mapId"
                      :placeholder="$t('operating.pleaseChosen')"
                      :show-count="true"
                      :maxHeight="600"
                      :options="mapTreeData"
                      :default-expand-level="1"
                      @input="nodeClick">
          </treeselect>
          <span>{{$t('history.date')}}:</span>
          <el-date-picker v-model="timeValue1"
                          type="datetime"
                          @change="change1"
                          :placeholder="$t('operating.StartTime')"
                          style="width:200px;">
          </el-date-picker>
          <el-date-picker v-model="timeValue2"
                          type="datetime"
                          @change="change2"
                          :placeholder="$t('operating.EndTime')"
                          style="width:200px;">
          </el-date-picker>
          <span>显示类型:</span>
          <el-select v-model="value1"
                     multiple
                     :placeholder="$t('operating.pleaseChosen')">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
          <span>
            <el-button icon="el-icon-search"
                       @click="query"
                       style="background-color:#f1a11e; color: #fff;">{{ $t('operating.search')}}</el-button>
          </span>
        </div>
      </el-header> -->

    <div class="context">
      <div id="map" />
      <div class="bottom_progress">
        <div>
          <div style="width:30px;height:30px;float:left;margin-right:30px">
            <el-button
              class="playbtn"
              type="primary"
              icon="al-icon-carplay"
              size="mini"
              circle
              @click="clickPlayBtn"
            />
          </div>
          <div
            style="float:left;"
            @mousedown="progressUIValue"
          >
            <el-slider
              v-model="progressIndex"
              style="width:400px;"
              :max="posLength"
              :step="1"
              :format-tooltip="formatTooltip"
              @change="progressValueChange"
            />
          </div>
          <div style="float:left;margin-left:30px">
            <el-select v-model="temp">
              <el-option
                v-for="item in tempCount"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
    </div>

    <!-- 左下角坐标显示和缩放比例 -->
    <div class="positiondiv">
      <span />
    </div>
    <div class="scalediv">
      <span />
    </div>

  </div>
</template>

<script>
import i18n from '@/utils/lang/index'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  TagStyle,
  _Style,
  updateOverlayPosition,
  FenceStyle,
  _TransMetric,
  _TransMetricFence,
  _dPR
} from '@/utils/historyMap.js'
import {
  webSockUrl,
  webSockStatisticsUrl,
  cameraServerUrl,
  baseUrl,
  initPicPath,
  webSockMonitorUrl,
  rateHeartShow
} from '@/utils/global'
import { Vector as VectorSource } from 'ol/source.js'
import { Vector as VectorLayer } from 'ol/layer.js'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { LineString } from 'ol/geom.js'
import { Style, Stroke } from 'ol/style.js'

import {
  getMapTree,
  getMap
} from '@/api/location'

import {
  getHistoryInfoDetail
} from '@/api/system/historyDisplayInfo.js'

export default {
  components: { Treeselect },
  data() {
    return {
      modelCount: [],
      model: null,
      queryParams: [],
      mapId: '',
      oldMapId: null,
      mapTreeData: [],
      radio: '1',
      timeValue1: new Date(new Date().getTime() - 1000 * 60 * 30),
      timeValue2: new Date(),
      TagSource: null,
      TagLayer: null,
      lineSource: null,
      lineLayer: null,
      temp: 100,
      trackData: [],
      currentPos: 1,
      feature_: null,
      setTImeOut_: null,
      tempCount: [
        {
          value: 50,
          label: '16x'
        },
        {
          value: 100,
          label: '8x'
        },
        {
          value: 200,
          label: '4x'
        },
        {
          value: 400,
          label: '2x'
        }
      ],
      posLength: 0,
      rloading: [],
      progressIndex: 0,
      value1: null,
      options: [],
      TD: [],
      allCount: 0,
      allsdf: []
    }
  },
  mounted() {
    this.initData()
  },
  beforeDestroy() {
    clearTimeout(this.setTImeOut_)
  },
  methods: {
    initData() {
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.mapTreeData = RES
          sendThis(this)
          this.mapId = RES[0].id
        }
      })
    },
    nodeClick() {
      if (this.oldMapId == this.mapId) {
        this.$message({
          message: i18n.t('realtime.areaQequired'),
          type: 'warning'
        })
      } else if (this.mapId !== undefined) {
        this.oldMapId = this.mapId
        getMap(this.mapId).then(res => {
          const RES = this.responseUse(res)
          if (RES != undefined) {
            $('#map').empty()
            Load_Map(baseUrl + '/file' + RES.mapPath, RES.mapActualX,
              RES.mapActualY,
              RES.mapPixelX,
              RES.mapPixelY,
              RES.mapPixelX / RES.mapActualX, [RES.mapOriginX, RES.mapOriginY], false)
            this.loadLayer()
          }
        })
      }
    },
    change1() {
      if (this.timeValue1 > this.timeValue2) {
        var tt = this.timeValue1.getTime()
        var ntt = tt + 1000 * 60 * 120
        this.timeValue2 = new Date(ntt)
      }
    },
    change2() {
      if (this.timeValue2 < this.timeValue1) {
        var tt = this.timeValue2.getTime()
        var ntt = tt - 1000 * 60 * 120
        this.timeValue1 = new Date(ntt)
      }
    },
    query() {
      this.allCount = 0
      this.allsdf = []
      // this.rloading = this.$loading({
      //   lock: true,
      //   text: i18n.t('areaTrackPlayback.loading'),
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0,0,0,0.7)'
      // })
      clearTimeout(this.setTImeOut_)
      this.currentPos = 0
      this.lineSource.clear(true)
      this.TagSource.clear(true)

      var startTime = this.v_FormatDateTime(new Date(this.timeValue1).getTime())
      var endTime = this.v_FormatDateTime(new Date(this.timeValue2).getTime())
      var param = {
        'mapId': this.mapId,
        'startTime': startTime,
        'endTime': endTime
      }
      getHistoryInfoDetail(param).then(res => {
        // this.rloading.close()
        const RES = this.responseUse(res)
        if (undefined != RES && RES.length > 0) {
          this.trackData = RES
          this.posLength = RES.length - 1
          this.options = []
          this.drawLine()
          $('.playbtn i').attr('class', 'al-icon-carpause')
        } else {
          this.$message({
            message: i18n.t('operating.switchQuery')
          })
        }
      })
    },
    // 加载地位图层和线图层,
    loadLayer() {
      this.TagSource = new VectorSource({
        wrapX: false
      })
      this.TagLayer = new VectorLayer({
        source: this.TagSource,
        style: function(feature) {
          return TagStyle(feature, 0)
        }
      })
      this.lineSource = new VectorSource({
        wrapX: false
      })
      this.lineLayer = new VectorLayer({
        source: this.lineSource,
        style: new Style({
          stroke: new Stroke({
            color: 'green',
            width: 3
          })
        })
      })
      _iMap.addLayer(this.lineLayer)
      _iMap.addLayer(this.TagLayer)
    },
    // 定时画线，定时更新点位位置
    drawLine() {
      var self = this
      self.progressIndex = self.currentPos
      var tag = self.TagSource.getFeatureById(self.trackData[self.currentPos].tagId)
      var pos_x = self.trackData[self.currentPos].posX
      var pos_y = self.trackData[self.currentPos].posY
      var name = self.trackData[self.currentPos].resourceName
      var type = self.trackData[self.currentPos].type
      var workTypeName = self.trackData[self.currentPos].workTypeName
      var tagId = self.trackData[self.currentPos].tagId
      if (tag != null) {
        if (tag.get('pos_x') - 0.3 > pos_x || tag.get('pos_x') + 0.3 < pos_x ||
          tag.get('pos_y') - 0.3 > pos_y || tag.get('pos_y') + 0.3 < pos_y) {
          // 坐标超过半米
          // 更新坐标
          tag.set('pos_x', pos_x)
          tag.set('pos_y', pos_y)
          tag.getGeometry().setCoordinates(_TransPixel([pos_x, pos_y]))
          var b = -1
          if (this.value1.length != 0) {
            for (var i = 0; i < this.value1.length; i++) {
              if (this.value1[i] == workTypeName) {
                b = 1
              }
            }
            if (b != -1) {
              tag.set('visible', true)
            } else {
              tag.set('visible', false)
            }
          } else {
            tag.set('visible', true)
          }
        }
      } else {
        if (type == null || type == '' || type == undefined) {

        } else {
          var point = new Point(_TransPixel([pos_x, pos_y]))
          var feature_ = new Feature(point)
          feature_.set('name', name)
          feature_.set('type', type)
          feature_.set('workTypeName', workTypeName)
          feature_.set('visible', true)
          feature_.set('pos_x', pos_x)
          feature_.set('pos_y', pos_y)
          feature_.setId(tagId)
          self.TagSource.addFeature(feature_)
          if (workTypeName == '' || workTypeName == undefined || workTypeName == null) {

          } else {
            this.options.push({
              value: workTypeName,
              label: workTypeName
            })
          }
          this.allCount++
        }
        if (this.allsdf.length == 0) {
          this.allsdf.push(tagId)
        } else {
          var b = -1
          for (var i = 0; i < this.allsdf.length; i++) {
            if (this.allsdf[i] == tagId) {
              b = i
            } else {

            }
          }
          if (b == -1) {
            this.allsdf.push(tagId)
          }
        }
        this.allCount = this.allsdf.length
      }

      self.currentPos++
      var temp_
      if (this.allCount == 0) {

      } else {
        temp_ = this.temp / this.allCount
      }

      if (self.currentPos < self.posLength || self.currentPos == self.posLength) {
        self.setTImeOut_ = setTimeout(function() {
          self.drawLine()
        }, temp_)
      } else {
        for (var i = 1; i < this.allCount; i++) {
          if (self.trackData[self.currentPos - i - 1].workTypeName == '') {
            return
          }
          var tag = self.TagSource.getFeatureById(self.trackData[self.currentPos - i - 1].tagId)
          var pos_x = self.trackData[self.currentPos - i - 1].posX
          var pos_y = self.trackData[self.currentPos - i - 1].posY
          tag.set('pos_x', pos_x)
          tag.set('pos_y', pos_y)
          tag.getGeometry().setCoordinates(_TransPixel([pos_x, pos_y]))
        }
      }
    },
    clickPlayBtn() {
      if (this.currentPos == 0) {
        return
      }
      const className = $('.playbtn i').attr('class')
      if (className === 'al-icon-carplay') {
        // 处于暂定状态
        $('.playbtn i').attr('class', 'al-icon-carpause')
        this.drawLine()
      } else if (className === 'al-icon-carpause') {
        // 处于播放状态
        $('.playbtn i').attr('class', 'al-icon-carplay')
        clearTimeout(this.setTImeOut_)
      }
    },
    progressUIValue() {
      clearTimeout(this.setTImeOut_)
      $('.playbtn i').attr('class', 'al-icon-carplay')
    },
    progressValueChange(val) {
      this.currentPos = val
      this.lineSource.clear(true)
      if (this.posLength != 0) {
        $('.playbtn i').attr('class', 'al-icon-carpause')
      }
      this.drawLine()
    },
    formatTooltip(val) {
      if (this.posLength != 0) {
        if (this.currentPos == this.posLength || this.currentPos > this.posLength) {
          return this.trackData[this.posLength - 1].speed
        } else {
          return this.trackData[this.currentPos].speed
        }
      }
    }
  }
}
</script>

<style scoped>
.container {
  height: calc(100vh - 50px);
  padding: 20px 20px 0 20px;
  /* background: blue; */
}
.handle-box {
  min-width: 1125px;
}

.handle-box * {
  float: left;
}

.handle-box span {
  line-height: 28px;
  margin-left: 30px;
}

.context {
  padding: 0;
  width: 100%;
  height: calc(100% - 60px);
  position: relative;
}
.context div {
  float: left;
}
#map {
  width: 100%;
  height: 100%;
}

.bottom_progress {
  position: absolute;
  width: 100%;
  height: 60px;
  bottom: 20px;
  display: grid;
  /* place-items: center;
   */
  place-content: end center;
}

>>> .vue-treeselect__control {
  width: 180px;
}

 /deep/ .el-button--mini.is-circle {
  width: 36px;
  height: 36px;
}
</style>
